<?php
class MenuControl extends BaseControl
{
    protected $cssFile;
    protected $jsFile;
    protected $tree;
    protected $treeHtml;
    protected $level = 1;
    protected $templateFile = 'Menu';

    public function MenuControl($root_id)
    {
        parent::__construct();
        $this->AddCss();
        BaseConfig::GetInstance()->AddSharedJs('controls/menu');
        $this->tree = CmsMenuModel::GetInstance()->GetTree($root_id);
    }

    protected function AddCss()
    {
        BaseConfig::GetInstance()->AddCss('controls/menu');
    }

    public function Render()
    {
        $this->Replace('tree', $this->GetTree());
        return parent::Render();
    }

    protected function GetTree()
    {
        TreeSet::Walk($this->tree, CmsMenuModel::GetInstance()->childKey, array($this, 'GetTreeNode'));
        return $this->treeHtml;
    }

    public function GetTreeNode($node, $depth)
    {
        $level = $depth + 1;
        if ($this->level < $level)
            $open = "<ul style='position: absolute; top: 0px; left: 0px; visibility: hidden;' class='level$level'>";
        else if ($this->level > $level)
        {
            $ulClose = str_repeat('</ul>', $this->level - $level);
            $open = "</li>$ulClose</li>";
        }
        else
            $open = isset($node['node_first']) ? null : '</li>';

        $url = $node['url'];
        $href = $url ? "href='$url'" : null;
        $html = "<li><a $href>{$node['name']}</a>";

        $this->treeHtml .= $open.$html;
        $this->level = $level;
    }
}
?>
